<template>
  <el-row :gutter="20">
    <el-col :span="12">
      <el-card class="card">
        <e-charts class="chart" :option="option3"/>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card class="card">
        <e-charts class="chart" :option="option2"/>
      </el-card>
    </el-col>
  </el-row>

  <el-row :gutter="20" style="margin-top: 20px">
    <el-col>
      <el-card class="card">
        <e-charts class="chart" :option="option4"/>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup>
import { ref, computed } from "vue"
import request from "@/util/request";

/**
 * 初始化类别数量
 */
const initTypeCount = async () => {
  const res = await request.get("home/typeCount");
  formatterTypeList(res.data.assetType)
}
initTypeCount();

let assetTypeName = ref([]);
const formatterTypeList = (row) => {
  for (let i = 0; i < row.length; i++) {
    assetTypeName.value.push({value: row[i].count, name: row[i].name})
  }
}

/**
 * 宁夏档案馆固定资产设备类别柱状图
 */
const option3 = computed(() => {
  return {
    title: {
      text: '宁夏档案馆固定资产设备类别柱状图',
      subtext: '截止当前时间',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: assetTypeName.value.map(d => d.name),
      axisTick: {
        alignWithLabel: true
      },
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: assetTypeName.value.map(d => d.value),
        type: 'bar',
        name: '总计',
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        }
      }
    ]
  }
})

/**
 * 初始化状态数量
 */
const initStatusCount = async () => {
  const res = await request.get("home/stsCount");
  formatterStatusList(res.data.assetStatus)
}
initStatusCount();

let assetStatusName = ref([])
const formatterStatusList = (row) => {
  for (let i = 0; i < row.length; i++) {
    assetStatusName.value.push({value: row[i].count, name: row[i].stsName})
  }
}

/**
 * 宁夏档案馆固定资产设备状态基本饼图
 */
const option2 = computed(() => {
  return {
    title: {
      text: '宁夏档案馆固定资产设备状态基本饼图',
      subtext: '截止当前时间（根据资产状态）',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: '50%',
        data: assetStatusName.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
})

//堆叠图基本数据
const optionData = ref({
  dates: [], //接口返回了时间的数据
  legends: [],//接口返回了哪些类别的数据，
  dataList: [] //按照legends中的类别顺序存储每一类的数据
})

//堆叠图数据初始化
const series = ref([]);

//堆叠图基本数据
const initStackData = async () => {
  const res = await request.get("home/assetAddStack");
  getStackData(res.data.resultList)
}
initStackData();

/**
 * 整理固定资产月增加数据，符合图表需求
 */
const getStackData = (list) => {
  // 1.整理时间月份数据===================================
  for (let key in list) {
    //第一层循环遍历每个月的数据
    let item = list[key].dataList
    let array = []
    //第二层循环用于遍历该月的资产类别数据
    for (let i in item) {
      //将类别添加到names数组中
      array.push(item[i].name)
    }
    //将names添加到原数组中
    list[key].names = array
  }
  // 2.获取所有的月份和图表的标签数据===================
  let legends = [];
  let dates = [];
  for (let key in list) {
    //原来时间信息的后两位可以得到真实的月份信息，利用Number()去除首位的0拼接 “月” 字，例：2023-01 =》2023-1月
    let mouth = Number(list[key].data.slice(-2)) + "月"
    list[key].newMonth = mouth;
    dates.push(mouth)
    legends.push(...list[key].names);
  }
  //遍历完成后资产类别数组需要进行去重
  legends = [...new Set(legends)]
  //以对象的形式返回{months:[],legends:[]}
  const assign = Object.assign({dates}, {legends});
  // 3.获取图表每月下各资产类别的数据=========================
  let valueList = [];
  for (let index in assign.legends) {
    let nums = [];
    //开始遍历所有数据
    for (let key in list) {
      let item = list[key]
      // console.log(item)
      //利用names字段判断是否有该类别的数据
      if (item.names.includes(assign.legends[index])) {
        //有 则查找该项
        let findItem = item.dataList.find((item) => {
          return item.name === assign.legends[index];
        })
        nums.push(findItem.count);
      } else {
        //没有 则直接插入0
        nums.push(0);
      }
    }
    valueList.push(nums);
  }
  // 4.重新整理数据=======================================
  optionData.value = Object.assign(optionData.value, assign, {dataList: valueList});
  setSeries(optionData.value)
}

/**
 * 根据图表的标签数据生成图
 */
const setSeries = (option) => {
  for (let index in option.legends) {
    series.value.push({
      name: option.legends[index],
      type: 'line',
      stack: 'Total',
      smooth: true,
      lineStyle: {
        width: 0
      },
      showSymbol: false,
      areaStyle: {
        opacity: 0.8,
      },
      emphasis: {
        focus: 'series'
      },
      data: option.dataList[index] //需要渲染的数据
    })
  }
}

/**
 * 宁夏档案馆固定资产月增加堆叠折线图
 */
const option4 = computed(() => {
  return {
    title: {
      text: '宁夏档案馆固定资产月增加堆叠折线图'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: optionData.value.legends,
    },
    toolbox: {
      feature: {
        saveAsImage: {} //下载图片
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: optionData.value.dates,
      }
    ],
    yAxis: [
      {
        type: "value",
        min: 0, //Y轴最小值
        max: 50, //Y轴最大值
        interval: 5, //Y轴间距
      }
    ],
    series: series.value
  }
})
</script>

<style lang="scss" scoped>
.chart {
  height: 400px;
}

.card {
  border: none;
  border-radius: 0;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}
</style>